package com.AsyncDemo.controller;

import com.AsyncDemo.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
public class AsyncArcicleController {
    @Autowired
    private ArticleService articleService;

    /**
     * 模拟获取文章后阅读量+1
     */
    @PostMapping("/article")
    public String getArticle() {
        // 查询文章
        String article = articleService.selectArticle();
        // 阅读量+1
        articleService.updateReadCount();
        System.out.println("getArticle文章阅读业务执行完毕");
        return article;
    }

    /**
     * 模拟获取文章后阅读量+1,指定线程池
     */
    @PostMapping("/articleByExecutor")
    public String getArticleByExecutor() {
        // 查询文章
        String article = articleService.selectArticle();
        // 阅读量+1
        articleService.updateReadCountByExecutor();
        System.out.println("getArticleByExecutor文章阅读业务执行完毕");
        return article;
    }

    /**
     * 模拟获取文章后阅读量+1,指定线程池
     */
    @PostMapping("/articleNoReturnByExecutor")
    public String getArticleNoReturnByExecutor() {
        // 查询文章
        String article = articleService.selectArticle();
        // 阅读量+1
        articleService.updateReadCountNoReturnByExecutor();
        System.out.println("getArticleNoReturnByExecutor文章阅读业务执行完毕");
        return article;
    }

    @GetMapping("/articleCompletableFuture")
    public String getArticleCompletableFuture() throws ExecutionException, InterruptedException {
        // 查询文章
        String article = articleService.selectArticle();
        // 阅读量+1
        CompletableFuture<Integer> future = articleService.updateReadCountHasResult();
        //无返回值的异步方法抛出异常不会影响Controller的主要业务逻辑
        //有返回值的异步方法抛出异常会影响Controller的主要业务逻辑
        int count = 0;
        // 循环等待异步请求结果
        while (true) {
            if(future.isCancelled()) {
                System.out.println("异步任务取消");
                break;
            }
            if (future.isDone()) {
                count = future.get();
                System.out.println(count);
                break;
            }
        }
        System.out.println("getArticleCompletableFuture文章阅读业务执行完毕");
        return article + count;
    }
}
